/*
 * Copyright (c) 2015, FPX and/or its affiliates. All rights reserved.
 * Use, Copy is subject to authorized license.
 */
package com.fpx.xms.api.base.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 
 * @author shiwei
 * @date 2015年6月24日
 */
public class CommonUtils {

	/**
	 * 将异常堆栈转换为字符串
	 * 
	 * @param aThrowable
	 *            异常
	 * @return String
	 */
	public static String getStackTrace(Throwable aThrowable) {
		String result = "";
		final Writer writer = new StringWriter();
		final PrintWriter printWriter = new PrintWriter(writer);
		try {
			aThrowable.printStackTrace(printWriter);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			printWriter.close();
		}
		return result;
	}

	public static String formatXml(String xml) throws IOException, DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new StringReader(xml));
		String requestXML = null;
		XMLWriter writer = null;
		if (document != null) {
			try {
				StringWriter stringWriter = new StringWriter();
				OutputFormat format = new OutputFormat();
				format.setNewlines(true);
				format.setIndentSize(4);
				format.setSuppressDeclaration(true);
				writer = new XMLWriter(stringWriter, format);
				writer.write(document);
				writer.flush();
				requestXML = stringWriter.getBuffer().toString().trim();
			} finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException e) {
					}
				}
			}
		}
		return requestXML;
	}
	
	public static String formatXml2(String xml) throws IOException, DocumentException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(new StringReader(xml));
		String requestXML = null;
		XMLWriter writer = null;
		if (document != null) {
			try {
				StringWriter stringWriter = new StringWriter();
				OutputFormat format = new OutputFormat();
				format.setSuppressDeclaration(true);
				format.setTrimText(true);
				writer = new XMLWriter(stringWriter, format);
				writer.write(document);
				writer.flush();
				requestXML = stringWriter.getBuffer().toString().trim();
			} finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException e) {
					}
				}
			}
		}
		return requestXML;
	}
	
	public static String getBasePath(HttpServletRequest request){
		String path = request.getContextPath();
	    String basePath = request.getScheme() + "://"
	            + request.getServerName() + ":" + request.getServerPort()
	            + path + "/";
	    return basePath;
	}
}
